package com.hongdee.insurance.order.service.impl;

import com.hongdee.common.util.DateUtils;
import com.hongdee.common.util.StringUtil;
import com.hongdee.common.util.TokenUtil;
import com.hongdee.insurance.Constant;
import com.hongdee.insurance.order.dao.ITInsuranceOrderDao;
import com.hongdee.insurance.order.entity.TInsuranceOrderExamLog;
import com.hongdee.insurance.order.service.TInsuranceCommissionExamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author 王帅
 * @className TInsuranceCommissioinExamServiceImpl
 * @type class
 * @description
 * @path com.hongdee.insurance.order.service.impl
 * @create 2017/6/12 10:25
 **/
@Service
public class TInsuranceCommissioinExamServiceImpl implements TInsuranceCommissionExamService {

    @Autowired
    private ITInsuranceOrderDao insuranceOrderDao;


    /**
     * 保险单佣金审核管理
     * @param data
     * @param uid
     * @param start
     * @param limit
     * @return
     * @throws Exception
     */
    @Override
    public Map page(Map data,String uid,String start,String limit) throws Exception {
        StringBuffer sql=new StringBuffer();
        List<String> params=new ArrayList<>();
        sql.append(" select * from ( ");
        sql.append(" select o.*,c.insurance_company_name,g.o_name, " +
                " sy.start_date syStartDate,sy.stop_date syStopDate,sy.contract_no syContractNo,sy.price syPrice,sy.commission syCommission,sy.commission_temp syCommissionTemp,sy.commission_exp syCommissionExp, " +
                " jq.start_date jqStartDate,jq.stop_date jqStopDate,jq.contract_no jqContractNo,jq.price jqPrice,jq.commission jqCommission,jq.commission_temp jqCommissionTemp,jq.commission_exp jqCommissionExp " +
                " from ( " +
                " SELECT o.*, car.car_brand, car.car_series, car.car_model, car.car_configure " +
                " FROM  t_insurance_order o, t_insurance_car car " +
                " WHERE  o.car_id = car.id ) o " +
                " left JOIN " +
                " t_insurance_company c " +
                " ON " +
                " o.insurance_company_id=c.id " +
                " left JOIN " +
                " t_bc_organ g " +
                " ON " +
                " o.company_id=g.id ");
        sql.append(" left join (select * from t_insurance_order_item where contract_type='jq') as jq on o.id=jq.order_id " +
                " left join (select * from t_insurance_order_item where contract_type='sy') as sy on o.id=sy.order_id ");
        sql.append(" where o.commission_type>'-1'  ");
//        params.add(TokenUtil.getCompanyId(uid));
       // Constant.setQueryByRoleDate(uid,sql,params,"o");
        //保险公司
        if(data.get("insuranceCompany")!=null && !"".equals(StringUtil.formatEmpty(data.get("insuranceCompany")))){
            sql.append(" and o.insurance_company_id=? ");
            params.add(StringUtil.formatEmpty(data.get("insuranceCompany")));
        }
        //出单日期 开始时间
        if(data.get("startDate")!=null && !"".equals(StringUtil.formatEmpty(data.get("startDate")))){
            sql.append(" and o.out_order_date >=? ");
            params.add(StringUtil.formatEmpty(data.get("startDate")));
        }
        //出单日期 结束时间
        if(data.get("stopDate")!=null && !"".equals(StringUtil.formatEmpty(data.get("stopDate")))){
            sql.append(" and o.out_order_date <=? ");
            params.add(StringUtil.formatEmpty(data.get("stopDate")));
        }
        //基盘类别
        if(data.get("baseType")!=null && !"".equals(StringUtil.formatEmpty(data.get("baseType")))){
            sql.append(" and o.base_type=? ");
            params.add(StringUtil.formatEmpty(data.get("baseType")));
        }
        //4s店(当前登录人的公司ID)
//        if(data.get("ssss")!=null && !"".equals(StringUtil.formatEmpty(data.get("ssss")))){
            sql.append(" and o.company_id=? ");
            params.add(TokenUtil.getCompanyId(uid));
//        }
        //费率差异
        if(data.get("diff")!=null && !"".equals(StringUtil.formatEmpty(data.get("diff")))){
            if("0".equals(StringUtil.formatEmpty(data.get("diff")))){
                sql.append(" and o.commission_type ='1' ");
                sql.append(" and o.price_warning_type ='1' ");
            }else {
                sql.append(" and (o.commission_type<>'1' or o.price_warning_type='0' or o.price_warning_type is null) ");
            }
        }
        //车牌号或VIN
        if (data.get("plateNum") != null && !"".equals(StringUtil.formatEmpty(data.get("plateNum")))) {
            if("plateNum".equals(StringUtil.formatEmpty(data.get("paramsKey")))){
                sql.append(" and o.plate_num like ?  ");
                params.add("%" + data.get("plateNum") + "%");
            }
            if("vin".equals(StringUtil.formatEmpty(data.get("paramsKey")))){
                sql.append(" and o.vin like ? ");
                params.add("%" + data.get("plateNum") + "%");
            }
            if("contractNo".equals(StringUtil.formatEmpty(data.get("paramsKey")))){
                sql.append(" and (sy.contract_no like ? or jq.contract_no like ?) ");
                params.add("%" + data.get("plateNum") + "%");
                params.add("%" + data.get("plateNum") + "%");
            }
            if("insured".equals(StringUtil.formatEmpty(data.get("paramsKey")))){
                sql.append(" and o.insured like ? ");
                params.add("%" + data.get("plateNum") + "%");
            }
        }
        if(data.get("commissionType")!=null && !"".equals(StringUtil.formatEmpty(data.get("commissionType")))){
            sql.append(" and o.commission_type=? ");
            params.add(StringUtil.formatEmpty(data.get("commissionType")));
        }
        sql.append(" )t order by create_time DESC ");
        return insuranceOrderDao.page(sql.toString(),params.toArray(),start,limit);
    }


    /**
     * 佣金审核
     * @param uid
     * @param data
     * @throws Exception
     */
    @Override
    public void examInsuranceCommission(String uid,String type,List<Map> data,String remark) throws Exception {
        StringBuffer sql=new StringBuffer();
        List<String> params=new ArrayList<>();
        sql.append(" update t_insurance_order set commission_type=?,commission_remark=?,commission_date=DATE_FORMAT(NOW(),'%Y-%m-%d') where id in( ");
        params.add(type);
        params.add(remark);
        for(int i=0;i<data.size();i++){
            sql.append("?");
            params.add(StringUtil.formatEmpty(data.get(i).get("id")));
            if(i<(data.size()-1)){
                sql.append(",");
            }
        }
        sql.append(" ) ");
        this.insuranceOrderDao.executeSQL(sql.toString(),params.toArray());
        this.examInsurancePrice(uid,type,data);
        this.addExamLogs(uid,type,data,remark);

    }



    /**
     * 审核保险保费状态
     * @param uid
     * @param type
     * @param data
     * @throws Exception
     */
    @Override
    public void examInsurancePrice(String uid,String type,List<Map> data) throws Exception {
        StringBuffer sql=new StringBuffer();
        StringBuffer sqlQu=new StringBuffer();
        List<String> params=new ArrayList<>();
        sql.append(" update t_insurance_order set price_warning_type=? where id in( ");
        sqlQu.append(" update T_Insurance_Quotation set price_warning_type=? where id in (select quotation_id from T_Insurance_Order where id in ( ");
        StringBuffer sqlParam=new StringBuffer();
        params.add(type);
        for(int i=0;i<data.size();i++){
            sqlParam.append("?");
            params.add(StringUtil.formatEmpty(data.get(i).get("id")));
            if(i<(data.size()-1)){
                sqlParam.append(",");
            }
        }
        sql.append(sqlParam.toString());
        sql.append(" ) ");
        sqlQu.append(sqlParam.toString());
        sqlQu.append(" )) ");
        this.insuranceOrderDao.executeSQL(sql.toString(),params.toArray());
        this.insuranceOrderDao.executeSQL(sqlQu.toString(),params.toArray());
    }

    public void addExamLogs(String uid,String type,List<Map> data,String remark) throws Exception {
        List<TInsuranceOrderExamLog> logList=new ArrayList<>();
        for(int i=0;i<data.size();i++){
            Map info=data.get(i);
            TInsuranceOrderExamLog log=new TInsuranceOrderExamLog();
            log.setCommissionDate(DateUtils.formatLongTime(System.currentTimeMillis(),DateUtils.YYYYMMDD));
            log.setCommissionType(type);
            log.setOrderId(StringUtil.formatEmpty(info.get("id")));
            log.setCreateTime(System.currentTimeMillis());
            log.setCreateUser(uid);
            log.setRemark(remark);
            logList.add(log);
        }
        this.insuranceOrderDao.saveOrUpdateList(logList);
    }

    /**
     * 根据保单ID 获得保单的审核日志信息
     * @param id
     * @return
     * @throws Exception
     */
    @Override
    public List<Map<String, Object>> findExalLogs(String id) throws Exception {
        String sql="select log.*,u.u_name from T_Insurance_Order_EXAM_LOG log left join t_bc_user u " +
                "ON " +
                "log.create_user=u.id where log.order_id=?";
        return this.insuranceOrderDao.list(sql,id);
    }
    
}
